<?php
/**
 * Created by IntelliJ IDEA.
 * User: TinND
 * Date: 4/3/14
 * Time: 1:57 PM
 */
if (isset($_GET['type'])) {
    $tempPath = $_FILES['file']['tmp_name'];
    list($hostPath) = explode($_SERVER['DOCUMENT_ROOT'], dirname(__FILE__));
    $rootPath = $hostPath . $_SERVER['DOCUMENT_ROOT'] . '/';
    $id = $_GET['id'];
    if (!isset($id)){
        echo json_encode(array('nodata' => true));
        return;
    }
    $rootPath='/Users/macuser/Sites/niFramework/'; /**/
    $productPath = $rootPath . 'img/product/' . $id . '/';
    $fileList = array();

    switch ($_GET['type']) {
        case 'avt':
            $avtPath = $productPath . 'avt/';

            if (is_dir($avtPath)) {
                if ($dh = opendir($avtPath)) {

                    while (($file = readdir($dh)) !== false) {
                        $ext = end(explode('.', $file));
                        if ($ext == "jpg" || $ext == "jpeg" || $ext == "png" || $ext == "gif")
//                            array_push($fileList, array('file' => "http://$_SERVER[HTTP_HOST]/img/product/" . $id . '/avt/'. $file));
                            array_push($fileList, array('file' => "http://$_SERVER[HTTP_HOST]/nihost/img/product/" . $id . '/avt/'. $file));
                    }
                    closedir($dh);
                }
            }
            break;
        case 'gallery':
            $avtPath = $productPath . 'gallery/';
            break;
        default:
            break;
    }

    header('Content-Type: application/json');
    if (count($fileList) > 0)
        echo json_encode($fileList);
    else
        echo json_encode(array('nodata' => true));

//    if (!file_exists($productPath)) {
//        mkdir($productPath, 0777, true);
//    }

//    $uploadPath = $productPath . $ext = 'icon.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);;
//
//    move_uploaded_file($tempPath, $uploadPath);
//
//    $answer = array('answer' => 'File transfer completed',
//        'upload' => $uploadPath);
//    header('Content-type: application/json');
//    echo json_encode($answer);
} else {
    echo 'No files';
}